package com.electric.controller;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.electric.common.CommonStringUtils;
import com.electric.common.FileUtil;
import com.electric.common.LoggerInterface;
import com.electric.entity.Attachment;
import com.electric.service.IAttachmentService;
import com.google.gson.Gson;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangbin
 * @since 2018-08-28
 */
@Controller
public class AttachmentController implements LoggerInterface{
	@Autowired
	private IAttachmentService attachmentService;
	
	// 上传图片
	@RequestMapping(value = "/uploadImages")
	@ResponseBody
	public void uploadImages(@RequestParam(value = "file", required = false) Object file,
			HttpServletRequest request,HttpServletResponse response, HttpSession session) throws Throwable {
		// 项目的真实路径
		String realPath = request.getSession().getServletContext().getRealPath(File.separator);
		logger.debug("项目真实路径：" + realPath);
		// 往上找两层
		File realPathFile = new File(realPath);
		realPath = realPathFile.getParentFile().getParent();
		logger.debug("存放上传文件的路径：" + realPath);
		
		List<Object> resultArray = new ArrayList<Object>();
		
		if(file instanceof List) {
			@SuppressWarnings("unchecked")
			List<MultipartFile> fileArray = (List<MultipartFile>) file;
			if(fileArray!=null && fileArray.size() > 0) {
				Iterator<MultipartFile> iterator = fileArray.iterator();
				
				while(iterator.hasNext()) {
					MultipartFile tempFile = iterator.next();
					Object result = upload(tempFile, "download" + File.separator + "images", realPath);
					resultArray.add(result);
				}
			}
		}
		else if(file instanceof MultipartFile){
			Object result = upload((MultipartFile) file, "download" + File.separator + "images", realPath);
			resultArray.add(result);
		}
		
		response.getWriter().write(new Gson().toJson(resultArray));
	}
	
	// 上传附件
	@RequestMapping(value = "/uploadAttachment")
	@ResponseBody
	public void uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request,HttpServletResponse response, HttpSession session) throws Throwable {
		// 项目的真实路径
		String realPath = request.getSession().getServletContext().getRealPath(File.separator);
		logger.debug("项目真实路径：" + realPath);
		// 往上找两层
		File realPathFile = new File(realPath);
		realPath = realPathFile.getParentFile().getParent();
		logger.debug("存放上传文件的路径：" + realPath);
		
		List<Object> resultArray = new ArrayList<Object>();
		
		if(file instanceof List) {
			@SuppressWarnings("unchecked")
			List<MultipartFile> fileArray = (List<MultipartFile>) file;
			if(fileArray!=null && fileArray.size() > 0) {
				Iterator<MultipartFile> iterator = fileArray.iterator();
				
				while(iterator.hasNext()) {
					MultipartFile tempFile = iterator.next();
					Object result = upload(tempFile, "download" + File.separator + "images", realPath);
					resultArray.add(result);
				}
			}
		}
		else if(file instanceof MultipartFile){
			Object result = upload((MultipartFile) file, "download" + File.separator + "images", realPath);
			resultArray.add(result);
		}
		
		response.getWriter().write(new Gson().toJson(resultArray));
	}
	
	/**
	 * 下载附件
	 * 
	 * @param req
	 * @param resp
	 * @param url
	 *            下载的附件存放地址
	 * @param fileName
	 *            下载的附件的名称
	 */
	@RequestMapping(value = "/downloadAttachments")
	@ResponseBody
	public void downloadAttachments(HttpServletRequest req, HttpServletResponse resp, String url,String fileName) {
		try {
			resp.setHeader("Expires", "0");
			resp.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			resp.setHeader("Pragma", "public");

			String userAgent = req.getHeader("User-Agent");
			// 针对IE或者以IE为内核的浏览器：
			if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
				fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
				fileName = fileName.replaceAll(" ", "%20");
				resp.setHeader("Content-disposition", "attachment;filename=" + fileName);
			} else {
				// 非IE浏览器的处理：
				fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
				resp.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
			}
			String prjPath = req.getScheme() + "://" + req.getServerName() + (req.getServerPort() == 80 ? "" : ":" + req.getServerPort()) + req.getContextPath();
			
			URL ul = new URL(prjPath + url);
			HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
			BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
			OutputStream os = resp.getOutputStream();
			byte[] by = new byte[1024];
			int len = 0;
			while ((len = bi.read(by)) != -1) {
				os.write(by, 0, len);
			}
			os.flush();
			os.close();
			bi.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param file
	 * @param request
	 * @param session
	 * @return
	 * @throws Throwable
	 */
	private Object upload(MultipartFile file,String savePath, String realPath) throws Throwable  {

		Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH) + 1;
		int day = now.get(Calendar.DAY_OF_MONTH);
		String path = year + File.separator + month + File.separator + day;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS");
		Attachment attachment = new Attachment();
		String time = sdf.format(date);
		String url = null;
		String[] name = { file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")),
				file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1,
						file.getOriginalFilename().length()) };
		name[0] = time;
		

		String fileRealPath = realPath + File.separator + savePath + File.separator + path;
		File myPath = new File(fileRealPath);
		if (!myPath.exists()) {
			// 若此目录不存在，则创建之
			myPath.mkdirs();
		}

		String newName = name[0] + '.' + name[1];
		String pathFileName = path + File.separator + newName;

		url = File.separator +savePath+ File.separator + pathFileName;
		url = url.replaceAll("\\\\", "/");
		try {
			// 拷贝文件
			FileUtil.copy(file.getInputStream(), fileRealPath + File.separator + newName);
			
			attachment.setDelFlag(0);
			attachment.setDownloadCounts(0);
			attachment.setFileName(file.getOriginalFilename());
			attachment.setFilePath(url);
			attachment.setFileType(name[1]);
			attachment.setInsertTime(new Date());
			attachment.setSeqId(CommonStringUtils.getUUID());
			
			attachmentService.insert(attachment);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", attachment.getSeqId());
		map.put("url", url);
		map.put("fileName", file.getOriginalFilename());
		return map;
	
	}
}

